<template>
  <div class="chat-container">
    <!-- 右下角图标 -->
    <div class="chat-icon" @click="toggleChat">
      <span v-if="!showChat">💬</span>
      <span v-else>✖</span>
    </div>

    <!-- 聊天窗口 -->
    <transition name="fade">
      <div v-show="showChat" class="chat-window">
        <div class="chat-header">
          <span style="font-family: 微软雅黑">青橙AI助手</span>
        </div>
        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in messages" :key="index"
               :class="['message', { 'user-message': message.isUser }]">
            <div v-if="message.isUser">{{ message.text }}</div>
            <div v-else v-html="parseMarkdown(message.text)"></div>
          </div>
        </div>
        <div class="chat-input-area">
          <input type="text" v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息...">
          <button @click="sendMessage">发送</button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { marked } from 'marked';
// 可选：添加代码高亮（需要 highlight.js）
import hljs from 'highlight.js';
export default {
  name: 'ChatWindow',
  data() {
    return {
      showChat: false,
      newMessage: '',
      messages: [],
      userMessage: '',
      isWaitingForAI: false // 防止重复请求
    };
  },
  methods: {

    toggleChat() {
      this.showChat = !this.showChat;

      if (this.showChat && this.messages.length === 0) {
        this.addAIMessage('您好！我是您的AI助手，有什么可以帮助您的吗？');
      }
    },
    parseMarkdown(text) {
      try {
        return marked(text);
      } catch (e) {
        console.error('Markdown 解析失败:', e);
        return `<pre>${text}</pre>`;
      }
    },
    async sendMessage() {
      const messageText = this.newMessage.trim();

      if (!messageText || this.isWaitingForAI) {
        return;
      }

      this.messages.push({
        text: messageText,
        isUser: true
      });
      this.newMessage = '';
      this.isWaitingForAI = true;

      const aiMessage = await this.getAIResponse(messageText)
      this.addAIMessage(aiMessage);
      this.isWaitingForAI = false;
      this.scrollToBottom();
    },
    async getAIResponse(userInput) {
      let aiMessage = '';
      this.userMessage = userInput
      await this.$api.ai.sendChat({userMessage: this.userMessage}).then(res => {
        aiMessage = res.result
      })
      return aiMessage;
    }, catch(error) {
      console.error('调用 AI 接口失败:', error);
      return '抱歉，AI 暂时无法回应。';
    },
    addAIMessage(text) {
      this.messages.push({
        text: text,
        isUser: false // AI消息标记为false
      });
      this.scrollToBottom();
    },

    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messagesContainer) {
          this.$refs.messagesContainer.scrollTop =
              this.$refs.messagesContainer.scrollHeight;
        }
      });
    }
  }
};
</script>

<style scoped>
.chat-container {
  position: relative;
}

/* 右下角图标样式 */
.chat-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 60px;
  height: 60px;
  background-color: #84d0ba;
  color: white;
  font-size: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  transition: transform 0.2s, box-shadow 0.2s;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.chat-icon:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

/* 聊天窗口样式 */
.chat-window {
  position: fixed;
  bottom: 90px;
  right: 20px;
  width: 350px;
  max-height: 500px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  z-index: 999;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 聊天窗口头部 */
.chat-header {
  padding: 15px;
  background: linear-gradient(45deg, #84d0ba, #ecb872);
  color: white;
  font-weight: bold;
  text-align: center;
  font-size: 18px;
  border-bottom: 1px solid #ddd;
}

/* 消息容器 */
.chat-messages {
  flex: 1;
  padding: 15px 15px 140px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

/* 单个消息样式 */
.message {
  background-color: #dcf8c6;
  margin-bottom: 20px; /* 增加底部间距 */
  padding: 10px 12px 10px 12px;
  border-radius: 10px;
  line-height: 1.4;
  word-wrap: break-word;
  max-width: 70%; /* 控制最大宽度 */
  /*min-width: 50px; !* 最小宽度 *!*/
  /*display: inline-block;*/
  clear: both;
}

.user-message {
  background-color: #dcf8c6;
  float: right;
  margin-left: auto;
  /*text-align: right;*/
}

.ai-message {
  background-color: #eaeaea;
  float: left;
  margin-right: auto;
  text-align: left;
}

/* 输入区域 */
.chat-input-area {
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}

.chat-input-area input {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 20px;
  margin-right: 10px;
  font-size: 16px;
  background-color: #f4f4f4;
}

.chat-input-area button {
  padding: 10px 20px;
  background-color: #84d0ba;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.chat-input-area button:hover {
  background-color: #45a049;
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}

.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */
{
  opacity: 0;
}
</style>
